package org.jinion.factory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jinion.configuration.DBconfig;
import org.jinion.constants.StringConstant;
import org.jinion.database.IDatabase;
import org.jinion.database.mysql.DatabaseMySql;

public class DatabaseFactory {
	private static final Log log = LogFactory.getLog(DatabaseFactory.class);

	public static IDatabase getDatabase() throws IOException,
			ClassNotFoundException, SQLException {
		return getDatabase(StringConstant.DEFAULT_CONFIG_FILE.getValue());
	}

	public static IDatabase getDatabase(String propertiesfileName)
			throws IOException, ClassNotFoundException, SQLException {
		DBconfig config = DBconfig.createDBconfig(propertiesfileName);
		return createDatabase(config);
	}
	
	public static IDatabase getDatabase(String driver, String url,
			String user, String password) throws ClassNotFoundException, SQLException {
		Class.forName(driver);
		Connection con = DriverManager.getConnection(url, user, password);
		DatabaseMySql db = new DatabaseMySql(con);
		return db;
	}
	
	public static IDatabase createDatabase(DBconfig config) {
		try {
			Class.forName(config.getDriveClass());
			Connection con = DriverManager.getConnection(config.getConnectionUrl(), config.getUsername(), config.getPassword());
			DatabaseMySql db = new DatabaseMySql(con);
			return db;
		} catch (ClassNotFoundException e) {
			log.error("driverClass not found error");
			return null;
		} catch (SQLException e) {
			log.error("connection can't establish error");
			return null;
		}
	}
	
	/**
	 * this method should judge the database type 
	 * from the properties file
	 * @return
	 */
	//TODO
	private static int getDatabaseType() {
		return 0;
	}
}
